package com.glsc.ngateway.platform.controller.smartbi;

import com.alibaba.excel.util.StringUtils;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.smartbi.SmartBiMenu;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.smartbi.SmartBiMenuRepository;
import com.glsc.ngateway.common.base.utils.IdUtil;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.google.common.base.Strings;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;


/**
 * BI报表菜单管理
 */
@RestController
@RequestMapping("/api/smartbi/menuManager")
@Api(tags = {"SmartBI报表，资管产品管理系统使用"})
public class SmartBiMenuController {

    Logger logger = LoggerFactory.getLogger(SmartBiMenuController.class);

    private UserCache userCache;

    @Resource
    private SmartBiMenuRepository smartBiMenuRepository;

    @Autowired
    public void setUserCache(UserCache userCache) {
        this.userCache = userCache;
    }


    @GetMapping("/listPage")
    public PlatformResponse<Page<SmartBiMenu>> listPage(
            @RequestParam(value = "systemId", required = false) String systemId,
            @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "level1Name", required = false) String level1Name,
            @RequestParam(value = "level2Name", required = false) String level2Name,
            @RequestParam(value = "level3Name", required = false) String level3Name) {
        PlatformResponse ret = null;
        try {
            if (pageNumber == null) {
                pageNumber = 1;
            }
            if (pageSize == null) {
                pageSize = 10;
            }

            Sort sort = Sort.by(Order.desc("status"), Order.asc("orderNum"));

            Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
            Page<SmartBiMenu> dto = null;

            dto = smartBiMenuRepository.findAll((root, query, cb) -> {
                Predicate predicate = root.isNotNull();

                predicate = cb.and(predicate, cb.equal(root.get("systemId").as(String.class), systemId));
                if (!Strings.isNullOrEmpty(level1Name)) {
                    predicate = cb.and(predicate, cb.equal(root.get("level1Name").as(String.class), level1Name));
                }

                if (!Strings.isNullOrEmpty(level2Name)) {
                    predicate = cb.and(predicate, cb.equal(root.get("level2Name").as(String.class), level2Name));
                }

                if (!Strings.isNullOrEmpty(level3Name)) {
                    predicate = cb.and(predicate, cb.equal(root.get("level3Name").as(String.class), level3Name));
                }
                return predicate;
            }, pageable);

            ret = PlatformResponse.successData(dto);

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg(e.getMessage());
        }

        return ret;
    }


    /**
     * 查询全部
     */
    @GetMapping("/listPageBylevel2Name")
    public PlatformResponse<Page<SmartBiMenu>> listBylevel2Name(
            @ApiParam(required = false, value = "系统标识ID") @RequestParam(value = "sysid", required = false) String sysid,
            @ApiParam(required = false, value = "一级菜单") @RequestParam(value = "level1Name", required = false) String level1Name,
            @ApiParam(required = false, value = "二级菜单") @RequestParam(value = "level2Name", required = false) String level2Name) {

        PlatformResponse ret = null;
        try {
            Sort sort = Sort.by(Direction.ASC, "orderNum");
            Pageable pageable = PageRequest.of(0, 10000, sort);
            Page<SmartBiMenu> dto = null;


            String systemId = sysid;//系统标识

            dto = smartBiMenuRepository.findAll((root, query, cb) -> {
                Predicate predicate = root.isNotNull();

                predicate = cb.and(predicate, cb.equal(root.get("systemId").as(String.class), systemId));
                if (!Strings.isNullOrEmpty(level2Name)) {
                    predicate = cb.and(predicate, cb.equal(root.get("level2Name").as(String.class), level2Name));
                }

                if (!Strings.isNullOrEmpty(level1Name)) {
                    predicate = cb.and(predicate, cb.equal(root.get("level1Name").as(String.class), level1Name));
                }

                //只返回有效状态的页面
                predicate = cb.and(predicate, cb.equal(root.get("status").as(Integer.class), 1));

                //只返回BI报表页面
                predicate = cb.and(predicate, cb.equal(root.get("menuType").as(String.class), 1));

                return predicate;
            }, pageable);

            ret = PlatformResponse.successData(dto);

        } catch (Exception e) {
            ret = PlatformResponse.failedMsg(e.getMessage());
        }

        return ret;
    }


    @PostMapping("/upsert")
    public PlatformResponse add(@RequestBody SmartBiMenu mysqlTMenu, HttpServletRequest request) {
        PlatformResponse ret = null;
        try {
            String user = userCache.getOpNo(request);
            if (StringUtils.isEmpty(mysqlTMenu.getMenuId()) || !smartBiMenuRepository.existsById(mysqlTMenu.getMenuId())) {
                mysqlTMenu.setCreateId(user);
                mysqlTMenu.setMenuId(IdUtil.getNextval(smartBiMenuRepository.findMaxMenuId(), "menu"));
                smartBiMenuRepository.save(mysqlTMenu);
            } else {
                SmartBiMenu dbrec = smartBiMenuRepository.findById(mysqlTMenu.getMenuId()).get();
                dbrec.setBiResid(mysqlTMenu.getBiResid());
                dbrec.setLevel1Name(mysqlTMenu.getLevel1Name());
                dbrec.setLevel2Name(mysqlTMenu.getLevel2Name());
                dbrec.setLevel3Name(mysqlTMenu.getLevel3Name());
                dbrec.setMenuType(mysqlTMenu.getMenuType());
                dbrec.setOrderNum(mysqlTMenu.getOrderNum());
                dbrec.setStatus(mysqlTMenu.getStatus());
                dbrec.setBiVersion(mysqlTMenu.getBiVersion());
                dbrec.setUpdateId(user);
                smartBiMenuRepository.save(dbrec);
            }
            return PlatformResponse.successData(mysqlTMenu);
        } catch (Exception e) {
            ret = PlatformResponse.failedMsg(e.getMessage());
        }
        return ret;
    }

    @PostMapping("/delete")
    public PlatformResponse delete(@RequestBody SmartBiMenu mysqlTMenu) {
        PlatformResponse response = null;
        try {
            mysqlTMenu.setStatus("0");
            smartBiMenuRepository.save(mysqlTMenu);
            response = PlatformResponse.successMsg("success");
        } catch (Exception e) {
            response = PlatformResponse.failedMsg(e.getMessage());
        }

        return response;
    }

}
